package com.extension.company.view.home;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.target.Target;
import com.bumptech.glide.request.transition.Transition;
import com.extension.company.admin.R;
import com.extension.company.common.mvc.BaseTitleActivity;
import com.extension.company.common.utils.ClipboardUtils;
import com.extension.company.common.widget.GridSpacingItemDecoration;
import com.extension.company.view.home.adapter.ShareImageAdapter;

import org.greenrobot.eventbus.Subscribe;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.InterruptedByTimeoutException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * intent 分享图片和文本
 */
public class ImageShareActivity extends BaseTitleActivity {
	@BindView(R.id.share_recycle)
	RecyclerView recyclerView;
	@BindView(R.id.share_img_btn)
	Button shareButton;
	@BindView(R.id.shareTitle)
	TextView shareTitle;

	private List<String> imgList = new ArrayList<>();
	private ShareImageAdapter shareImageAdapter;

	@Override
	public int getMainLayout() {
		return R.layout.activity_image_share;
	}

	@Override
	public void initView() {
		setTitle("推广素材");
		updateSuccessView();
		recyclerView.setLayoutManager(new GridLayoutManager(this, 4, GridLayoutManager.VERTICAL, false));
		recyclerView.addItemDecoration(new GridSpacingItemDecoration(4, 10, false));
		shareImageAdapter = new ShareImageAdapter(this, imgList);
		recyclerView.setAdapter(shareImageAdapter);
	}

	@Override
	public void initData() {
		imgList.add("http://img1.juimg.com/170310/330850-1F31000491410.jpg");
		imgList.add("http://img1.gtimg.com/tech/pics/hv1/247/217/1003/65275657.jpg");
		imgList.add("http://y1.ifengimg.com/dce7142117a6922d/2014/0512/rdn_5370a3700adcc.jpg");
		imgList.add("http://fdfs.xmcdn.com/group6/M02/0F/D8/wKgDhFUn8rXQpoUgAACpapzkKKQ24.jpeg");
		imgList.add("http://img1.gtimg.com/cul/pics/hv1/33/145/1855/120658383.jpg");
		imgList.add("http://photocdn.sohu.com/20100818/Img274292909.jpg");
		imgList.add("http://b-ssl.duitang.com/uploads/blog/201404/08/20140408231323_5FjPX.jpeg");
		imgList.add("http://news.cnhubei.com/a/10001/201906/a9c8a57272fea2f74e0d34c977aca733.jpeg");
		imgList.add("http://img.mp.itc.cn/upload/20160925/401275fe8c314440be8517152b6a8907_th.jpg");

		shareImageAdapter.notifyDataSetChanged();
		int y;
		for (int i = 0; i < imgList.size(); i++) {
			RequestOptions requestOptions = new RequestOptions().override(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL);
			Glide.with(this).asBitmap().load(imgList.get(i)).apply(requestOptions).into(new mySimpleTarget(i));
		}

		ClipboardUtils.copyText(this, shareTitle.getText().toString()); // 将数据复制到粘贴板上

	}

	@Override
	public void initListener() {

	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// TODO: add setContentView(...) invocation
		ButterKnife.bind(this);
	}

	@OnClick({R.id.share_img_btn})
	public void onViewClicked(View v) {
		switch (v.getId()) {
			case R.id.share_img_btn:
				originShare();
				break;
			default:
				break;
		}
	}

	/**
	 * 原始分享
	 */
	private void originShare() {
		Intent share_intent = new Intent();
		ArrayList<Uri> imageUris = new ArrayList<Uri>();
		Uri uri;
		String fileName = Environment.getExternalStorageDirectory() + File.separator + "zwk";
		Log.d("zwk", "文件名称是:" + fileName);
		File file = new File(fileName);

		File[] files = file.listFiles();
		for (File f : files) {
			Log.d("zwk", "子文件名曾：" + f.getName());
			imageUris.add(Uri.fromFile(f));
		}
//		share_intent.setAction(Intent.ACTION_SEND_MULTIPLE);//设置分享行为
//		share_intent.setType("image/*");//设置分享内容的类型image/png
//		share_intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, imageUris);
//		startActivity(Intent.createChooser(share_intent, "Share"));

//		share_intent.setType("text/plain");
//		share_intent.putExtra(Intent.EXTRA_TEXT, "分享的内容");
//		startActivity(Intent.createChooser(share_intent, "share"));

//		Intent localIntent = new Intent("android.intent.action.SEND");
//		localIntent.putExtra("android.intent.extra.TEXT", "内容");
//		localIntent.putExtra("sms_body", "内容");
//		localIntent.putExtra("Kdescription", "内容");
//
//		localIntent.putExtra("android.intent.extra.STREAM", imageUris);
//		localIntent.setType("image/*");
//		startActivity(Intent.createChooser(localIntent, "Share"));
		Intent intent = new Intent(Intent.ACTION_SEND);
		intent.setType("image/*");
		intent.putExtra(Intent.EXTRA_STREAM, imageUris.get(0));
		intent.putExtra(Intent.EXTRA_TEXT, "呢哦人能够");
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivity(Intent.createChooser(intent, "分享的标题"));

	}


	/**
	 * 实例化的子类
	 */
	public class mySimpleTarget extends SimpleTarget<Bitmap> {
		private int y;

		public mySimpleTarget(int y) {
			this.y = y;
		}

		@Override
		public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
			Bitmap tempBitmip = resource;
			//图片名称
			String mFileName = "zwk" + File.separator + y + ".jpg";
			//图片路径
			File tempPath = Environment.getExternalStorageDirectory();
			//保存图片
			File newFile = saveBitmap(tempPath, mFileName, tempBitmip);
			String backgroundPath = newFile.getPath();
			if (backgroundPath != null) {

				// 其次把文件插入到系统图库
				try {
					MediaStore.Images.Media.insertImage(getContentResolver(),
							newFile.getAbsolutePath(), backgroundPath, null);
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				}

				// 最后通知图库更新
				sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
						Uri.fromFile(new File(newFile.getPath()))));

				Toast.makeText(ImageShareActivity.this, "图片成功保存至:/storage/emulated/0/zwk", Toast.LENGTH_SHORT).show();

			} else {
				Toast.makeText(ImageShareActivity.this, "保存失败", Toast.LENGTH_SHORT).show();
			}

		}
	}

	/**
	 * 保存图片方法
	 */

	public File saveBitmap(File path, String imgName, Bitmap bitmap) {

		File f = new File(path, imgName);
		//创建文件夹
		if (!f.getParentFile().exists()) {
			f.getParentFile().mkdirs();
		}
		try {
			FileOutputStream out = new FileOutputStream(f);
			bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
			out.flush();
			out.close();
			return f;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return null;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}

	}
}
